package cn.dankal.flyaudio.personal.setting;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import com.zhihu.matisse.internal.entity.IncapableCause;
import com.zhihu.matisse.internal.entity.Item;

import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import api.UserServiceFactory;
import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import cn.dankal.basiclib.DKUserManager;
import cn.dankal.basiclib.common.camera.CamerImageBean;
import cn.dankal.basiclib.protocol.PersonalProtocol;
import cn.dankal.basiclib.rx.AbstractDialogSubscriber;
import cn.dankal.basiclib.util.ClipboardUtils;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.basiclib.widget.titlebar.SingleTextTitle;
import cn.dankal.business.pojo.ReasonBean;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.current.post.Glide4Engine;
import cn.dankal.flyaudio.oss.view.AliUploadActivity;

import static butterknife.OnTextChanged.Callback.AFTER_TEXT_CHANGED;

/**
 * @author vane
 * @since 2018/8/8
 */
@Route(path = PersonalProtocol.FEEDBACK)
public class FeedbackActivity extends AliUploadActivity {

    @BindView(R.id.et_feedback)
    EditText etFeedback;
    @BindView(R.id.tv_text_size)
    TextView tvTextSize;
    String content;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_feedback;
    }

    @Override
    protected void initComponents() {
        super.initComponents();
        addTitleBar(new SingleTextTitle("意见反馈"));
        mAdapter.setType(1);

    }


    @OnClick(R.id.bt_submit)
    public void onViewClicked() {
        String content = etFeedback.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            showToast("请输入您的宝贵的意见..");
            return;
        }
        showLoadingDialog();

        // 如果有图片就提交图片，如果没有就提交纯文本
        if (elements != null && elements.size() > 0) {

            for (Uri element : elements) {
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(element,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String mPicturePath;
                if (columnIndex == -1) {
                    mPicturePath = CamerImageBean.getInstance().getImagePath();
                } else {
                    mPicturePath = cursor.getString(columnIndex);
                }
                Log.d("PickPicture", mPicturePath);
                cursor.close();

                String objectName = "fg_" + DKUserManager.getUserInfo().getId() + "_" + System.currentTimeMillis() + ".jpg";
                finalKeys.add(objectName);
                mService.asyncPutData(objectName, mPicturePath);
            }
        } else {
            submit(content);
        }

    }

    @Override
    public void uploadComplete() {
        submit(etFeedback.getText().toString().trim());
    }

    private void submit(String con) {
        String[] keys = new String[finalKeys.size()];
        finalKeys.toArray(keys);
        if (finalKeys != null) {
            ClipboardUtils.copyText(this, DKUserManager.getUserToken().token);
            ClipboardUtils.copyText(this, TextUtils.join(", ", finalKeys));
        }
        UserServiceFactory.feedback(new HashMap<String, Object>() {{
            put("content", TextUtils.isEmpty(con) ? "" : con);
            put("imgUrl", finalKeys);
        }}).subscribe(new AbstractDialogSubscriber<ReasonBean>(this) {
            @Override
            public void onNext(ReasonBean reasonBean) {
                showToast("反馈成功，感谢您宝贵的意见~");
                postDelayedToFinish();
            }
        });
    }

    /**
     * EditText可以输入的字数
     */
    int textCount = 0;

    @OnTextChanged({R.id.et_feedback})
    void beingInputted() {
        textCount = etFeedback.getText().toString().length();
    }

    @OnTextChanged(value = {R.id.et_feedback}, callback = AFTER_TEXT_CHANGED)
    void afterInputted() {
        String afterText = textCount + "/200";
        tvTextSize.setText(afterText);
    }
    @Override
    public void addPhoto() {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .capture(true)
                .addFilter(new Filter() {
                    @Override
                    protected Set<MimeType> constraintTypes() {
                        return new HashSet<MimeType>() {{
                            add(MimeType.PNG);
                        }};
                    }
                    @Override
                    public IncapableCause filter(Context context, Item item) {

                        return null;
                    }
                })
                .captureStrategy(new CaptureStrategy(true, "cn.dankal.flyaudio.provider.download"))
                .maxSelectable(9 - elements.size())
//                      .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
//                      .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new Glide4Engine())
                .forResult(REQUEST_CODE_CHOOSE);
    }


}
